package com.user.action;

import com.admin.service.SoftWareClassifyService;
import com.data.bean.Account;
import com.data.entity.TempUpdateApk;
import com.data.util.CheckDataUtils;
import com.data.util.DatabaseIdUtils;
import com.data.util.FinalStringUtils;
import com.data.util.ImageLookUtils;
import com.user.bean.App;
import com.user.bean.AppDetail;
import com.user.service.SoftwareService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

import static com.data.util.FinalStringUtils.*;
import static com.data.util.JsonUtils.returnMassageUtils;

/**
 * 软件上传服务管理
 *
 * @author:HingLo
 * @create 2017-09-15 9:47
 **/
@Controller
@RequestMapping("/SoftwareAction/user/")
public class SoftwareAction {
    private static Logger logger = Logger.getLogger(SoftwareAction.class);
    @Autowired
    private SoftwareService softwareService;
    @Autowired
    private SoftWareClassifyService softWareClassifyService;

    /**
     * 进入到上传界面
     *
     * @return
     */
    @GetMapping("inputUpload")
    public String inputSoftwareAction(HttpServletRequest request) {
        //都动态加载软件的信息
        List<?> list = softwareService.findSoftwareAction();
        request.setAttribute("dataMap", list);
        return "/WEB-INF/user/softwareUpload";

    }


    /**
     * 上传软件的临时文件
     *
     * @return
     */
    @PostMapping("uploadTempSoftware")
    @ResponseBody
    public Map<String, Object> uploadTempSoftwareAciton(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) {
        String filename = file.getOriginalFilename();
        //获取文件的后缀
        String s = filename.substring(filename.lastIndexOf("."));
        StringBuilder path = new StringBuilder(FinalStringUtils.TEMPATH);
        boolean bool = false;
        if (CheckDataUtils.stringUtils(s)) {
            Map<String, Object> map;
            if (s.equals(".apk")) {
                String apkName = request.getSession().getId() + s;
                //拼接临时文件的的存入名称
                path.append("apk/").append(apkName);
                map = softwareService.uploadTempSoftwareService(path.toString(), file, "apk");
                if (map.get(ERROR) == null) {
                    //避免界面获取不到Error的值而报错
                    request.setAttribute(ERROR, null);
                    request.getSession().setAttribute(APKINFO, map);
                    return returnMassageUtils(true, apkName);

                } else {
                    ///将需错误的信息提示到界面中
                    return returnMassageUtils(false, (String) map.get("error"));
                }

            } else if (CheckDataUtils.iconUtils(s)) {
                String imageName = DatabaseIdUtils.getDataIdOne() + s;
                //拼接临时文件的的存入名称
                path.append("image/").append(request.getSession().getId()).append("/").append(imageName);
                map = softwareService.uploadTempSoftwareService(path.toString(), file, "image");
                return map != null ? returnMassageUtils(true, imageName) : returnMassageUtils(bool, "图片上传失败，请重新上传");
            }
        }
        return returnMassageUtils(false, "文件格式不正确");
    }

    /**
     * 提交上传软件信息
     *
     * @return
     */
    @PostMapping("submitUpload")
    public String softwareUploadAction(@RequestParam("minImage") CommonsMultipartFile minImage, @RequestParam("medImage") CommonsMultipartFile medImage, App app, AppDetail appDetail, String menu, String image, HttpServletRequest request) {
        Account account = (Account) request.getSession().getAttribute("Account");
        String id = account.getId();
        boolean bool = false;
        if (id != null) {
            Map<String, Object> map = (Map<String, Object>) request.getSession().getAttribute(APKINFO);
            //设置软件的大小
            app.setSize((Float) map.get(SOFTWARESIEZE));
            //设置软件包名称
            app.setPackagename((String) map.get(PACKAGENAME));
            //设置软件版本
            app.setVersion((String) map.get(VERSIONNAME));

            //设置软件MD5值
            app.setMd5((String) map.get(MD5));
            app.setUid(id);
            //获取登录用户的身份

            //内置上传用户
            if (account.getTypes() == FinalStringUtils.BUILT_ADMIN) {
                //如果是内置账号上传用户，默认为软件为激活状态
                app.setState(FinalStringUtils.ACTIVE);
            } else {
                //其他账号上传的用户，设置App的状态需要审核
                app.setState(FinalStringUtils.DEFAULT);
            }
            String sid = request.getSession().getId();
            CommonsMultipartFile[] file = {minImage, medImage};
            bool = softwareService.softwareUploadService(app, id, sid, appDetail, image, menu, file);
        }
        //文件上传成功就到主页，失败就定向到404界面
        return bool ? "redirect:/indexUserAction/user/index" : "404";
    }

    /**
     * 根据软件的类型来查找软件的一级菜单信息
     *
     * @param param
     * @return
     */
    @RequestMapping("userMenu")
    @ResponseBody
    public List<?> getOneMenuAction(Integer param) {
        if (param == FinalStringUtils.SOFTTYPE || param == FinalStringUtils.GAMETYPE) {
            return softWareClassifyService.findMenuOneService(param);
        } else {
            return null;
        }

    }

    /**
     * 根据id来查找二级菜单的信息
     *
     * @param fid
     * @param type
     * @return
     */
    @RequestMapping("userTwoMenu")
    @ResponseBody
    public List<?> getTwoMenuAction(String fid, Integer type) {
        if (CheckDataUtils.stringUtils(fid)) {
            return softWareClassifyService.findMenuTwoService(fid, type);
        }
        return null;
    }

    /**
     * 删除未上架的应用
     *
     * @param id
     * @return
     */
    @ResponseBody
    @PostMapping("deleteSoftware")
    public String deleteSoftwareAction(String id, String md5) {
        boolean bool = false;
        if (CheckDataUtils.stringUtils(id, md5)) {
            id = id.trim();
            md5 = md5.trim();
            bool = softwareService.deleteSoftwareService(id, md5);
        }
        return String.valueOf(bool);
    }

    /**
     * 申请下线软件
     *
     * @param id
     * @return
     */
    @ResponseBody
    @PostMapping("downOffline")
    public String downOfflineSoftwareAction(@RequestParam("id") String id, String contents) {
        boolean bool = false;
        contents = "默认拒绝的理由";
        if (CheckDataUtils.stringUtilsID(id) && CheckDataUtils.stringUtils(contents)) {
            bool = softwareService.downOfflineSoftwareService(id, contents);
        }
        return String.valueOf(bool);
    }


    /**
     * 查看软件的详细信息
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("softwareInfo")
    public String lookSoftwareAction(@RequestParam("id") String id, HttpServletRequest request) {

        request.setAttribute("App", softwareService.findSoftwareInfoService(id, 1));
        request.setAttribute("Icon", softwareService.findSoftwareInfoService(id, 2));
        request.setAttribute("Menu", softwareService.findSoftwareInfoService(id, 3));
        return "/WEB-INF/user/softwareInfo";
    }

    /**
     * 查看软件图片信息
     *
     * @param id
     * @param name
     * @param response
     */
    @GetMapping("looksoftwareIcon")
    public void looksoftwareIconAction(String id, String name, HttpServletResponse response) {
        byte[] inputStream = ImageLookUtils.lookImageNameUtils(id, name);
        ImageLookUtils.responseImage(inputStream, response);
    }

    /**
     * 软件升级操作,上传软件与图片到临时文件夹
     *
     * @param request
     * @return
     */

    @PostMapping("updateSoftwareTemp")
    @ResponseBody
    public Map<String, Object> updateSoftwareTempAction(@RequestParam("file") CommonsMultipartFile file, String rid, HttpServletRequest request) {
        String filename = file.getOriginalFilename();
        //获取文件的后缀
        String s = filename.substring(filename.lastIndexOf("."));

        if (CheckDataUtils.stringUtils(rid, s)) {
            if (s.trim().equals(".apk")) {
                //如果上传的是软件信息
                Map map = softwareService.uploadTempSoftwareService(file, ".apk", rid);
                if (map.get(ERROR) == null) {
                    //避免界面获取不到Error的值而报错
                    request.setAttribute(ERROR, null);
                    request.getSession().setAttribute(APKINFO, map);
                    return returnMassageUtils(true, "软件上传成功");
                } else {
                    ///将需错误的信息提示到界面中
                    return returnMassageUtils(false, map.get(ERROR));
                }

            } else if (CheckDataUtils.iconUtils(s)) {
                //若果上传的是图片信息
                Map map;
                String imageName = DatabaseIdUtils.getDataIdOne() + s;
                StringBuilder path = new StringBuilder(FinalStringUtils.IMAGEPATH).append(rid).append("/").append(imageName);
                map = softwareService.uploadTempSoftwareService(file, s, path.toString());
                return map != null ? returnMassageUtils(true, imageName) : returnMassageUtils(false, "图片上传失败，请重新上传");
            }
        }
        return returnMassageUtils(false, "文件格式不正确");
    }

    /**
     * 软件升级操作
     *
     * @param medImage      应用图标
     * @param tempUpdateApk
     * @param request
     * @return
     */
    @PostMapping("updateSoftware")
    public String updateSoftwareAction(@RequestParam(value = "medImage", required = false) CommonsMultipartFile medImage, TempUpdateApk tempUpdateApk, HttpServletRequest request) {
        Account account = (Account) request.getSession().getAttribute("Account");
        String rid = tempUpdateApk.getRid();
        boolean bool = false;
        if (rid != null) {
            Map<String, Object> map = (Map<String, Object>) request.getSession().getAttribute(APKINFO);
            if (map == null || map.size() == 0) {
                return "404";
            }

            CommonsMultipartFile[] file = {medImage, medImage};
            bool = softwareService.softwareUpdateUploadService(file, map, account, tempUpdateApk);
        }
        //文件上传成功就到主页，失败就定向到404界面
        return bool ? "redirect:/indexUserAction/user/index" : "404";

    }

    /**
     * 进入到软件更新界面
     *
     * @param rid
     * @param request
     * @return
     */
    @GetMapping("inputUpdateSoftware")
    public String updateSoftwareAction(String rid, HttpServletRequest request) {
        if (CheckDataUtils.stringUtilsID(rid)) {
            //读取软件的信息
            App app = softwareService.findSoftwareInfoService(rid);
            request.setAttribute("app", app);

            request.setAttribute("icon", softwareService.findSoftwareInfoService(rid, 2));

            return "/WEB-INF/user/updateSoftware";
        }
        return "404";

    }


}
